package com.tuling.jucdemo.sync;

import lombok.extern.slf4j.Slf4j;

/**
 * @author :tangweiliang
 * @date : 2022/11/8 22:55
 * 未来的你会感谢现在努力的你
 *
 * Java共享内存模型带来的线程安全问题
 * 思考： 两个线程对初始值为 0 的静态变量一个做自增，一个做自减，各做
 * 5000 次，结果是 0 吗？
 */
@Slf4j
public class SyncDemo {
    private static int count = 0;

    public static void increment(){
        count++;
    }

    public static void delcrement(){
        count--;
    }

    public static void main(String[] args) throws InterruptedException {
       Thread t1 = new Thread(()->{
           for (int i = 0; i < 5000; i++) {
               increment();
           }
       },"t1");

       Thread t2 = new Thread(()->{
           for (int i = 0; i < 5000; i++) {
               delcrement();
           }
       },"t2");

       t1.start();
       t2.start();
       t1.join();
       t2.join();

       log.info("count={}", count);

    }
}
